package com.ymttest.business.service.shenqi;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ymttest.database.sqlwapper.godmch.mch_infoWapper;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.shenqisettlement.parameter.bean.GetCurrencyConfigBean;
import com.shop2cn.iapi.shenqisettlement.parameter.bean.ProviderBean;
import com.shop2cn.iapi.shenqisettlement.parameter.resp.GetCurrencyConfigResp;
import com.shop2cn.iapi.shenqisettlement.service.GetCurrencyConfigCall;
import com.shop2cn.iapi.agentproducts.parameter.AddAgentProductBean;
import com.shop2cn.iapi.agentproducts.parameter.CatalogDto;
import com.shop2cn.iapi.agentproducts.parameter.CatalogPriceDto;
import com.shop2cn.iapi.agentproducts.parameter.DetailsCatalogDto;
import com.shop2cn.iapi.agentproducts.parameter.EditProductRebateBean;
import com.shop2cn.iapi.agentproducts.parameter.ImportAgentProductBean;
import com.shop2cn.iapi.agentproducts.parameter.ModifyAgentProductBean;
import com.shop2cn.iapi.agentproducts.parameter.ModifyCatalogDto;
import com.shop2cn.iapi.agentproducts.parameter.ProductDetailsDto;
import com.ymatou.iapi.dguser.parameter.UserCreateBean;
import com.ymatou.iapi.godmch.parameter.CreateCodeBean;
import com.ymatou.iapi.godmch.parameter.addProviderBean;
import com.ymatou.iapi.godmch.parameter.applyAgentBean;
import com.ymatou.iapi.godmch.parameter.applySupplierBean;
import com.ymatou.iapi.godmch.parameter.approveAgentBean;
import com.ymatou.iapi.godmch.parameter.bindmchBean;
import com.ymatou.iapi.godmch.parameter.createIndepMchBean;
import com.ymatou.iapi.godmch.parameter.createagentBean;
import com.ymatou.iapi.godmch.parameter.createmchBean;
import com.ymatou.iapi.godmch.parameter.editmchBean;
import com.ymatou.iapi.godmch.parameter.registerByCodeBean;
import com.ymatou.iapi.godmch.parameter.setShareTypeBean;
import com.ymatou.iapi.godmch.service.CreateCodeCall;
import com.ymatou.iapi.godmch.service.addProviderCall;
import com.ymatou.iapi.godmch.service.applyAgentCall;
import com.ymatou.iapi.godmch.service.applySupplierCall;
import com.ymatou.iapi.godmch.service.bindmchCall;
import com.ymatou.iapi.godmch.service.createIndepMchCall;
import com.ymatou.iapi.godmch.service.getAgentPromotePicCall;
import com.ymatou.iapi.godmch.service.registerByCodeCall;
import com.ymatou.iapi.godmch.service.setShareTypeCall;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.AddAgentProductCallService;
import com.ymttest.business.service.DGUserCallService;
import com.ymttest.business.service.shenqi.bean.ShenqiUserSet;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.model.agent_type;
import com.ymttest.database.model.invite_code;
import com.ymttest.database.model.shenqisettlement.BankRequiredField;
import com.ymttest.database.sqlwapper.DGUserWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.godmch.invite_codeWapper;
import com.ymttest.database.sqlwapper.godmch.mch_relationWapper;
import com.ymttest.database.sqlwapper.shenqisettlement.BankRequiredFieldWrapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

public class DGSQBaseService {

	private static long autotest_goodsOwnerId = Long.valueOf(EnvSetup
			.getData("autotest_goodsOwnerId"));
	private static String autotest_goodsOwnerName = String.valueOf(EnvSetup
			.getData("autotest_goodsOwnerName"));
	
	private static YmtCatalogsIWapper ymtCatalogsIWapper =  new YmtCatalogsIWapper();

	public static int createSeller() throws Exception {

		UserCreateBean u = DGUserCallService.initUsercreateBean();
		u.setIscs(true);
		u.setUserType(1);
		u.setAppSource(DGUserCallService.DG_SellerWxApp);
		u.setWxAppName(DGUserCallService.TestWxsqSeller);

		Integer sellerId = DGUserCallService.UserCreateCall(u);

		return sellerId;
	}
	
	public static int createGoodsOwner(String country) throws Exception {
		
		int goodsOwnerId = createSeller();
		
		createmchBean bean = GodmchManageCallService
				.InitcreatemchBeanForChannel(goodsOwnerId);
		bean.setCountry(country);

		GodmchManageCallService.createmchCallForChannel(bean);

		return goodsOwnerId;
	}

	public static int createGoodsOwner(int goodsOwnerId, String country)
			throws Exception {

		createmchBean bean = GodmchManageCallService
				.InitcreatemchBeanForChannel(goodsOwnerId);
		bean.setCountry(country);

		GodmchManageCallService.createmchCallForChannel(bean);

		return goodsOwnerId;
	}

	public static createmchBean bindChannel(int parentId) throws Exception {

		return bindChannel(parentId, null, null);
	}

	public static createmchBean bindChannel(int parentId, String country, Integer sellerId)
			throws Exception {
		
		createmchBean createmchBean = new createmchBean();
		
		if (sellerId == null) {
			
			createmchBean = GodmchManageCallService
					.InitcreatemchBeanForChannel(createSeller());

			if (country != null)
				createmchBean.setCountry(country);
			
			if (createmchBean.getCountry().equalsIgnoreCase("CHN"))
				createmchBean.setCode("GNQDS");

			GodmchManageCallService.createmchCallForChannel(createmchBean);
			
			sellerId = createmchBean.getMchId();
		} else {
			
			createmchBean.setMchId(sellerId);
			createmchBean.setCountry(country);
		}
		
		bindmchBean bean = new bindmchBean();
		bindmchCall call = new bindmchCall();

		if (parentId != (int) autotest_goodsOwnerId) {

			CreateCodeBean createCodeBean_a = GodmchManageCallService
					.InitcreateCodeBeanForAgent(parentId, false);
			GodmchManageCallService
					.editMchInfo(
							createCodeBean_a.getMchId(),
							ShenqiUserSet.isAutotestUser((long) parentId) ? "自动化测试-交易专用"
									: "title" + createCodeBean_a.getMchId(),
							"http://pic1.ymatou.com/G01/M00/3F/CD/rBBlD1yTdyCAe7ruAABImnwn1Sc744_1_1_o.png",
							"autotest" + parentId);
			Thread.sleep(3000);
			CreateCodeCall createcall_a = GodmchManageCallService
					.createCodeCall(createCodeBean_a);

			bean.setMchId(sellerId);
			bean.setCode(createcall_a.getCode());
		} else {
			bean.setMchId(sellerId);
			bean.setCode("174");
		}

		call.setData(bean);
		call.callService();

		return createmchBean;
	}
	
	public static createmchBean bindShengPayChannel(int parentId, String country)
			throws Exception {

		createmchBean createmchBean = GodmchManageCallService
				.InitcreatemchBeanForChannel(createSeller());

		if (country != null)
			createmchBean.setCountry(country);

		GodmchManageCallService.createmchCallForChannel(createmchBean);
		
		// 设置支付方式为盛付通
		GodmchManageCallService.SetPayMode(createmchBean.getMchId());

		bindmchBean bean = new bindmchBean();
		bindmchCall call = new bindmchCall();

		if (parentId != (int) autotest_goodsOwnerId) {

			CreateCodeBean createCodeBean_a = GodmchManageCallService
					.InitcreateCodeBeanForAgent(parentId, false);

			CreateCodeCall createcall_a = GodmchManageCallService
					.createCodeCall(createCodeBean_a);

			bean.setMchId(createmchBean.getMchId());
			bean.setCode(createcall_a.getCode());
		} else {
			bean.setMchId(createmchBean.getMchId());
			bean.setCode("174");
		}

		call.setData(bean);
		call.callService();

		return createmchBean;
	}

	public static createmchBean createAgent(int parentId, String country)
			throws Exception {

		int userId = DGSQBaseService.createSeller();
		
		if (parentId != autotest_goodsOwnerId)
			
			GodmchManageCallService
					.editMchInfo(
							(int) parentId,
							ShenqiUserSet.isAutotestUser((long) parentId) ? "自动化测试-交易专用"
									: "title" + parentId,
							"http://pic1.ymatou.com/G01/M00/3F/CD/rBBlD1yTdyCAe7ruAABImnwn1Sc744_1_1_o.png",
							ShenqiUserSet.isAutotestUser((long) parentId) ? "自动化测试-交易专用"
									: "autotest" + parentId);

		List<createmchBean> beanList = GodmchManageCallService
				.InitcreatemchBeanForAgent(parentId, userId);
		beanList.get(0).setCountry(country);

		GodmchManageCallService.createmchCallForAgent(beanList
				.toArray(new createmchBean[0]));

		// 创建代理类型
		createagentBean createagentBean = GodmchManageCallService
				.InitCreateAgentTypeBean(userId);
		GodmchManageCallService.CreateAgentTypeCall(createagentBean);

		return beanList.get(0);
	}
	
	public static createmchBean createInheritedAgent(int parentId) {
		
		int userId;
		
		try {
			userId = DGSQBaseService.createSeller();
			
			invite_codeWapper invitecodeWapper = new invite_codeWapper();
			
			Map<String, Object> map = new HashMap<>();
			
			map.put("mchId", parentId);
			map.put("agentModel", 2);
			map.put("expireTime", Calendar.getInstance().getTime());
			
			List<invite_code> codeList = invitecodeWapper.selectby(map);
			
			if (codeList.size() >= 0) {
				//设置自动继承邀请码
				CreateCodeBean createbean = GodmchManageCallService.InitcreateCodeBeanForAgent(parentId, false);
				createbean.setAgentModel(2);
				
				GodmchManageCallService.createCodeCall(createbean);
				
				map.remove("expireTime");
				
				codeList = invitecodeWapper.selectby(map).stream()
						.sorted(Comparator.comparing(invite_code::getSeqId).reversed())
						.collect(Collectors.toList());
			}

			createmchBean createmchBean_agent = new createmchBean();

			createmchBean_agent.setMchId(userId);
			createmchBean_agent.setCode(codeList.get(0).getInviteCode());
			createmchBean_agent.setCountry("CHN");
			createmchBean_agent.setNickName("测试");
			
			Thread.sleep(2000);
			
			GodmchManageCallService.createmchCallForAgent(createmchBean_agent);
			
			return createmchBean_agent;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 创建分销小店代理
	 * @param parentId
	 * @return
	 */
	public static createmchBean createRetailShopAgent(int parentId, BigDecimal rebateRate) {
		
		int userId;
		
		try {
			userId = DGSQBaseService.createSeller();
			
			invite_codeWapper invitecodeWapper = new invite_codeWapper();
			
			Map<String, Object> map = new HashMap<>();
			
			map.put("mchId", parentId);
			map.put("agentModel", 2);
			map.put("expireTime", Calendar.getInstance().getTime());
			
			List<invite_code> codeList = invitecodeWapper.selectby(map);
			
			if (codeList.size() >= 0) {
				// 设置自动继承邀请码
				CreateCodeBean createbean = GodmchManageCallService
						.InitcreateCodeBeanForRetailShopAgent(parentId, rebateRate, false);
				
				createbean.setAgentModel(2);

				GodmchManageCallService.createCodeCall(createbean);

				map.remove("expireTime");

				codeList = invitecodeWapper
						.selectby(map)
						.stream()
						.sorted(Comparator.comparing(invite_code::getSeqId)
								.reversed()).collect(Collectors.toList());
			}

			createmchBean createmchBean_agent = new createmchBean();

			createmchBean_agent.setMchId(userId);
			createmchBean_agent.setCode(codeList.get(0).getInviteCode());
			createmchBean_agent.setCountry("CHN");
			createmchBean_agent.setNickName("测试");
			
			Thread.sleep(2000);
			
			GodmchManageCallService.createmchCallForAgent(createmchBean_agent);
			
			return createmchBean_agent;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 初始化代理商品发布
	 * 
	 * @param goodsOwnerId
	 *            商户id
	 * @param goodsOwnerName
	 *            商户名称
	 * @param setAgentPrice
	 *            是否设置给下级代理
	 */
	public static String createAgentProduct(int goodsOwnerId,
			String goodsOwnerName, boolean setAgentPrice) throws IOException {
		return createAgentProduct(goodsOwnerId, goodsOwnerName, setAgentPrice, null);
	}

	/**
	 * 初始化代理商品发布
	 * 
	 * @param goodsOwnerId
	 *            商户id
	 * @param goodsOwnerName
	 *            商户名称
	 * @param setAgentPrice
	 *            是否设置给下级代理
	 * @param currency 币种
	 */
	public static String createAgentProduct(int goodsOwnerId,
			String goodsOwnerName, boolean setAgentPrice, String currency)
			throws IOException {

		return createAgentProduct(goodsOwnerId, goodsOwnerName, setAgentPrice,
				currency, false);
	}

	/**
	 * 初始化代理商品发布
	 * 
	 * @param goodsOwnerId
	 *            商户id
	 * @param goodsOwnerName
	 *            商户名称
	 * @param setAgentPrice
	 *            是否设置给下级代理
	 * @param currency 币种
	 * @param isAllVirtualStock 是否都有虚拟库存
	 */
	public static String createAgentProduct(int goodsOwnerId,
			String goodsOwnerName, boolean setAgentPrice, String currency,
			boolean isAllVirtualStock) throws IOException {

		AddAgentProductBean addAgentProductBean = AddAgentProductCallService
				.initAddAgentProduct(goodsOwnerId, goodsOwnerName,
						setAgentPrice);
		
		addAgentProductBean.setBrandId(10104);

		if (currency != null)
			addAgentProductBean.setCurrency(currency);
		
		List<CatalogDto> agentCatalogIdList = addAgentProductBean
				.getCatalogList();

		agentCatalogIdList.stream().forEach(catalogDto -> catalogDto.setCostPrice(20d));
		
		if (isAllVirtualStock) {

			for (CatalogDto catalogDto : agentCatalogIdList) {
				
				catalogDto.setVirtualStock(10);
				catalogDto.setStock(10);
			}
		} else {
			
			agentCatalogIdList.get(0).setVirtualStock(10);
			agentCatalogIdList.get(0).setStock(10);
		}

		return AddAgentProductCallService.AddAgentProduct(addAgentProductBean);
	}

	/**
	 * 创建组合商品
	 * @param goodsOwnerId
	 * @param currency
	 * @param isMultiCode
	 * @return
	 * @throws Exception 
	 */
	public static String createComposeAgentProduct(int goodsOwnerId, String currency, Boolean isMultiCode) throws Exception {

		String productId = SqTradingProductService
				.AddComposeAgentProduct(goodsOwnerId, currency, isMultiCode);

		return productId;
	}
	
	public static DetailsCatalogDto getProductStock(int goodsOwnerId,
			String productId, String catalogId) throws ClientProtocolException,
			IOException {

		ProductDetailsDto productDetailsDto = AddAgentProductCallService
				.selectProductDetails(goodsOwnerId, productId);

		List<DetailsCatalogDto> catalogs = productDetailsDto.getCatalogList()
				.stream()
				.filter(catalogDto -> catalogDto.getCatalogId().equalsIgnoreCase(catalogId))
				.collect(Collectors.toList());

		if (catalogs.size() > 0)
			return catalogs.get(0);
		else
			return null;
	}

	/**
	 * 初始化导入商品到我的小铺Bean
	 * 
	 * @param sellerId
	 *            商户Id
	 * @param sellerName
	 *            商户名称
	 * @param parentProductId
	 *            上级商户Id
	 * @param parentUserId
	 *            上级商品Id
	 * @param isSetAgentPrice
	 *            是否设置代理价
	 * @return
	 */
	public static AgentProductBean importAgentProduct(int sellerId,
			String sellerName, String parentProductId, int parentUserId,
			boolean isSetAgentPrice) throws InterruptedException, IOException {

		ImportAgentProductBean bean = AddAgentProductCallService
				.initImportAgentProduct(sellerId, sellerName, parentProductId,
						parentUserId, isSetAgentPrice);

		String agentProductId = AddAgentProductCallService
				.ImportAgentProduct(bean);
		
		List<String> agentCatalogIdList = getCatalogIdList(agentProductId);

		AgentProductBean agentProductBean = new AgentProductBean();
		
		agentProductBean.setProductId(agentProductId);
		agentProductBean.setCatalogList(agentCatalogIdList);
		agentProductBean.setAgentCatalogPriceList(getCatalogPriceList(agentCatalogIdList));

		return agentProductBean;
	}
	
	public static List<String> getCatalogIdList(String productId) throws InterruptedException {
		
		List<YmtCatalogsI> ymtCatalogsIList = ymtCatalogsIWapper
				.selectCatalogsByProductId(productId);
		List<String> catalogIdList = new ArrayList<>();
		
		ymtCatalogsIList.forEach(p -> {
			catalogIdList.add(p.getsCatalogId());
			Logger.comment(p.getsCatalogId());
		});
		
		return catalogIdList;
	}
	
	public static List<CatalogPriceDto> getCatalogPriceList(List<String> catalogIdList) throws InterruptedException {
		
		List<CatalogPriceDto> ymtCatalogPriceList = ymtCatalogsIWapper
				.getPriceByCatalogIds(catalogIdList).stream()
				.sorted(Comparator.comparing(CatalogPriceDto::getCatalogId).reversed())
				.collect(Collectors.toList());
		
		return ymtCatalogPriceList;
	}

	public static AgentProductBean createProductByChain(List<Long> sellerIds,
			boolean agent) throws Exception {

		String productId = DGSQBaseService.createAgentProduct(sellerIds.get(0)
				.intValue(), autotest_goodsOwnerName, true);

		AgentProductBean agentProductBean = DGSQBaseService.importAgentProduct(
				sellerIds.get(1).intValue(), "", productId, sellerIds.get(0)
						.intValue(), true);
		
		return DGSQBaseService.importAgentProduct(sellerIds.get(2).intValue(),
				"", agentProductBean.getProductId(), sellerIds.get(1)
						.intValue(), false);
	}

	public static List<BankRequiredField> getBankRequiredFieldsByCountryCode(
			String countryCode) {

		BankRequiredFieldWrapper wrapper = new BankRequiredFieldWrapper();
		List<BankRequiredField> bankRequiredFieldList = wrapper
				.selectByCountryCode(countryCode);

		return bankRequiredFieldList;
	}
	
	public static GetCurrencyConfigResp getCurrencyConfig(String currency) throws ClientProtocolException, IOException{
		
		GetCurrencyConfigBean getcurrencyconfigBean = new GetCurrencyConfigBean();
		GetCurrencyConfigCall getcurrencyconfigCall = new GetCurrencyConfigCall();
		
		getcurrencyconfigBean.setCurrency(currency);
		
		getcurrencyconfigCall.setData(getcurrencyconfigBean);
		getcurrencyconfigCall.callService();

		GetCurrencyConfigResp currencyConfigResp = getcurrencyconfigCall
				.getCurrencyConfigResp();
		
		return currencyConfigResp;
	}
	
	public static int createProvider(String country) throws Exception {
		
		addProviderBean bean = new addProviderBean();
		addProviderCall call = new addProviderCall();
		
		int userId_channel = createGoodsOwner(country);

		// 渠道
		createmchBean createBean = GodmchManageCallService
				.InitcreatemchBeanForChannel(userId_channel);
		GodmchManageCallService.createmchCallForChannel(createBean);

		List<String> countryList = new ArrayList<>();
		countryList.add("CAN");
		countryList.add("JPN");
		countryList.add("GBR");
		countryList.add("USA");
		countryList.add(country);

		List<Integer> serviceType = new ArrayList<>();

		serviceType.add(3);
		bean.setProviderId(userId_channel);
		bean.setServiceType(serviceType);
		bean.setCountryList(countryList);

		call.setData(bean);
		call.callService();
		
		return userId_channel;
	}
	
	public static void createServiceRelation(long providerId,long mchId,int serviceType) throws Exception {
		
		GodmchManageCallService.InitAddServiceRelation((int)providerId, (int)mchId, serviceType);
	}
	
	public static ProviderBean getChannelProviders(Long mchId) {

		YmatouEasyCall getChannelProvidersCall = new YmatouEasyCall("", "POST",
				"JSON");
		StringBuilder getChannelProvidersString = new StringBuilder();
		ProviderBean providerBean = null;

		getChannelProvidersString.append("{\"mchId\":" + mchId + "}");

		getChannelProvidersCall
				.setUrl("http://godmch.iapi.shop2cn.com/api/service/getChannelProviders");

		getChannelProvidersCall.setData(getChannelProvidersString.toString());

		try {
			getChannelProvidersCall.callService();

			Logger.comment(getChannelProvidersCall.getReturnData());
			
			providerBean = new ProviderBean();

			JSONObject result = new JSONObject(
					getChannelProvidersCall.getReturnData())
					.optJSONObject("result");

			if (result.has("providerList")) {

				JSONArray providerList = result.getJSONArray("providerList");

				for (int i = 0; i < providerList.length(); i++) {
					
					JSONObject providerVo = providerList.getJSONObject(i);
					
					if (providerVo.getBoolean("enabled")) {
						
						JSONArray serviceTypeList = providerVo.getJSONArray("serviceType");
						
						// 如果serviceType有3，则返回providerId，否则继续寻找
						for (int j = 0; j < providerList.length(); j++) {
							
							if (serviceTypeList.getInt(j) == 3) {
								providerBean.setProviderId(providerVo.getLong("providerId"));
								providerBean.setBindTime(providerVo.getString("bindTime"));
								
								return providerBean;
							}	
							else
								continue;
						}
					} else {
						// 服务商被禁用
						providerBean.setProviderId(9999L);
						
						return providerBean;
					}
				}
				
				// 不是软件服务商
				providerBean.setProviderId(9998L);
				
				return providerBean;
				
			} else {
				return null;
			}
		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}
	}
	
	public static Integer createIndependenceMch(String country)
			throws Exception, JSONException {
		
		try {
			
			createIndepMchBean bean = GodmchManageCallService.InitCreateIndepMchBean();
			
			bean.setMchShareType(2);
			bean.setAgentInvite(true);
			bean.setAgentPublish(true);
			bean.setCountry(country);

			createIndepMchCall createIndepMchCall = GodmchManageCallService
					.CreateIndepMchCall(bean);
			
			// 数据库插入小程序配置,dguser.wxappconfig
//			DGUserWapper wapper = new DGUserWapper();
//			wapper.insertWxAppConfig(createIndepMchCall.getmchId());
			 
			int mchId = createIndepMchCall.getmchId();
			 
//			setShareTypeBean setShareTypeBean = new setShareTypeBean();
//			setShareTypeCall setShareTypeCall = new setShareTypeCall();
//
//			setShareTypeBean.setMchId((int) mchId);
//			setShareTypeBean.setMchShareType(1);
//			setShareTypeBean.setMchStatus(0);
//			setShareTypeBean.setRemark("autotest");
//
//			setShareTypeBean.setPulishDomestic(true);
//			setShareTypeBean.setMchSideBuy(2);
//
//			setShareTypeCall.setData(setShareTypeBean);
//			setShareTypeCall.callService();

			return mchId;
		} catch (JSONException e) {
			e.printStackTrace();
			
			return null;
		}
	}

	public static Integer createIndependenceAgent(long parentId, long rootMchId, String country, Integer agentModel)
			throws Exception {
		
		// 创建邀请码，必须有头像和title
		GodmchManageCallService
				.editMchInfo(
						(int) parentId,
						ShenqiUserSet.isAutotestUser((long) parentId) ? "自动化测试-交易专用"
								: "title" + parentId,
						"http://pic1.ymatou.com/G01/M00/3F/CD/rBBlD1yTdyCAe7ruAABImnwn1Sc744_1_1_o.png",
						ShenqiUserSet.isAutotestUser((long) parentId) ? "自动化测试-交易专用"
								: "autotest" + parentId);
		
		// 设置邀请码
		invite_codeWapper invitecodeWapper = new invite_codeWapper();
		
		Map<String, Object> map = new HashMap<>();
		
		map.put("mchId", parentId);
		map.put("agentModel", agentModel);
		map.put("expireTime", Calendar.getInstance().getTime());
		
		List<invite_code> codeList = invitecodeWapper.selectby(map);
		
		if (codeList.size() >= 0) {
			
			if (agentModel == 1) {

				// 设置自动继承邀请码
				CreateCodeBean createCodeBean = GodmchManageCallService
						.InitcreateCodeBeanForAgent((int) parentId, false);

				createCodeBean.setAgentModel(agentModel);

				GodmchManageCallService.createCodeCall(createCodeBean);
				
			} else {

				// 设置自动继承邀请码
				CreateCodeBean createCodeBean = GodmchManageCallService
						.InitcreateCodeBeanForRetailShopAgent((int) parentId,
								BigDecimal.TEN, false);

				createCodeBean.setAgentModel(agentModel);

				GodmchManageCallService.createCodeCall(createCodeBean);
			}
			
			Thread.sleep(2000);

			map.remove("expireTime");

			codeList = invitecodeWapper
					.selectby(map)
					.stream()
					.sorted(Comparator.comparing(invite_code::getSeqId)
							.reversed()).collect(Collectors.toList());
		}
		
		registerByCodeBean registerByCodeBean = GodmchManageCallService
				.initRegisterByCode((int) parentId, codeList.get(0)
						.getInviteCode());
		
		// 独立商户的mchId必须是根商户的mchId，根据inviteCode来绑定上级
		registerByCodeBean.setMchId((int) rootMchId);
		
		registerByCodeBean.setAppKey("appsqSeller_" + rootMchId);
		registerByCodeBean.setCountry(country);
		
		// 根据code创建子商户
		Integer childMchId = GodmchManageCallService.registerByCodeCall(registerByCodeBean)
				.getRegMchId();
		
		// 数据库插入小程序配置,dguser.wxappconfig
		DGUserWapper wapper = new DGUserWapper();
		wapper.insertWxAppConfig(childMchId);
		
		// 创建代理类型
		createagentBean createagentBean = GodmchManageCallService
				.InitCreateAgentTypeBean(childMchId);
		
		createagentBean.setAgentMode(agentModel);
//		createagentBean.setRebateRate(rebateRate);
		
		GodmchManageCallService.CreateAgentTypeCall(createagentBean);
		
		return childMchId;
	}
	
	public static void createIndependenceAgent(long parentId,
			long rootMchId, long sellerId, String country, Integer agentModel)
			throws Exception {
		
		// 创建邀请码，必须有头像和title
		GodmchManageCallService
				.editMchInfo(
						(int) parentId,
						ShenqiUserSet.isAutotestUser((long) parentId) ? "自动化测试-交易专用"
								: "title" + parentId,
						"http://pic1.ymatou.com/G01/M00/3F/CD/rBBlD1yTdyCAe7ruAABImnwn1Sc744_1_1_o.png",
						ShenqiUserSet.isAutotestUser((long) parentId) ? "自动化测试-交易专用"
								: "autotest" + parentId);
		
		// 设置邀请码
		invite_codeWapper invitecodeWapper = new invite_codeWapper();
		
		Map<String, Object> map = new HashMap<>();
		
		map.put("mchId", parentId);
		map.put("agentModel", agentModel);
		map.put("expireTime", Calendar.getInstance().getTime());
		
		List<invite_code> codeList = invitecodeWapper.selectby(map);
		
		if (codeList.size() >= 0) {
			
			if (agentModel == 1) {

				// 设置自动继承邀请码
				CreateCodeBean createCodeBean = GodmchManageCallService
						.InitcreateCodeBeanForAgent((int) parentId, false);

				createCodeBean.setAgentModel(agentModel);

				GodmchManageCallService.createCodeCall(createCodeBean);
				
			} else {

				// 设置自动继承邀请码
				CreateCodeBean createCodeBean = GodmchManageCallService
						.InitcreateCodeBeanForRetailShopAgent((int) parentId,
								BigDecimal.TEN, false);

				createCodeBean.setAgentModel(agentModel);

				GodmchManageCallService.createCodeCall(createCodeBean);
			}
			
			Thread.sleep(2000);

			map.remove("expireTime");

			codeList = invitecodeWapper
					.selectby(map)
					.stream()
					.sorted(Comparator.comparing(invite_code::getSeqId)
							.reversed()).collect(Collectors.toList());
		}
		
//		registerByCodeBean registerByCodeBean = GodmchManageCallService
//				.initRegisterByCode((int) parentId, codeList.get(0)
//						.getInviteCode());
//		
//		registerByCodeBean.setAppKey("appsqSeller_" + rootMchId);
//		registerByCodeBean.setCountry(country);
//		
//		Integer childMchId = GodmchManageCallService.registerByCodeCall(registerByCodeBean)
//				.getRegMchId();
		
		// 创建代理类型
		createagentBean createagentBean = GodmchManageCallService
				.InitCreateAgentTypeBean((int)sellerId);
		
		createagentBean.setAgentMode(agentModel);
//		createagentBean.setRebateRate(rebateRate);
		
		GodmchManageCallService.CreateAgentTypeCall(createagentBean);
//		return sellerId;
	}
	
	/**
	 * 独立商户申请代理并审核通过
	 * 
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws JSONException
	 * @throws InterruptedException
	 */
	public static applyAgentCall applyAndapproveAgent(Integer mchId)
			throws ClientProtocolException, IOException, JSONException, InterruptedException {

		// 考虑到需要使用代理，所以返回申请代理call，代理Id：applyCall.getAgentId()
		Thread.sleep(5000);// 休眠目的是为了创建独立商户，把对应的配置 同步到用户那边，然后用户 拿到配置再创建代理
		// 2：申请代理
		applyAgentBean applyBean = GodmchManageCallService.InitApplyAgentBean();
		applyBean.setMchId(mchId);
		applyBean.setAppKey("appsqSeller_" + mchId);
		applyBean.setCountry("USA");
		applyAgentCall applyCall = GodmchManageCallService.ApplyAgentCall(applyBean);
		// 代理类型
		createagentBean agentBean = GodmchManageCallService.InitCreateAgentTypeBean(applyBean.getMchId());
		GodmchManageCallService.CreateAgentTypeCall(agentBean);
		// 查询代理类型
		Map<String, Object> map = new HashMap<>();
		map.put("mchId", applyBean.getMchId());
		List<agent_type> list = GodmchManageCallService.agentTypeWapper.selectby(map);
		// 3:审核代理
		approveAgentBean approveAgentBean = new approveAgentBean();
		approveAgentBean.setMchId(applyBean.getMchId());
		approveAgentBean.setAgentId(applyCall.getAgentId());
		approveAgentBean.setAgentType(list.get(0).getAgentType());
		approveAgentBean.setAgentMode(1);

		GodmchManageCallService.ApproveAgentCall(approveAgentBean);

		return applyCall;
	}
	
	/**
	 * 创建具有分销关系的代理
	 * @param mchId
	 * @param n
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws InterruptedException 
	 * @throws JSONException 
	 */
	public static int createPromoters(Integer mchId, int n)
			throws ClientProtocolException, IOException, JSONException,
			InterruptedException {
		
		// 申请 审核代理1
		applyAgentCall applyAgent = DGSQBaseService
				.applyAndapproveAgent(mchId);
		
		Integer agentId = applyAgent.getAgentId();
		
		for (int i = 0; i < n; i++) {
			
			editmchBean editmchBean = GodmchManageCallService
					.IniteditmachBean(agentId);
			GodmchManageCallService.editmachCall(editmchBean);

			registerByCodeBean bean = new registerByCodeBean();
			registerByCodeCall call = new registerByCodeCall();

			getAgentPromotePicCall getAgentPromotePicCall = GodmchManageCallService
					.getAgentPromotePic(agentId);
			
			Thread.sleep(5000);
			bean = GodmchManageCallService.initRegisterByCode(mchId,
					getAgentPromotePicCall.getInviteCode());
			call = GodmchManageCallService.registerByCodeCall(bean);
			
			agentId = call.getRegMchId();
		}
		
		return agentId;
	}
	
	/**
	 * 修改货头的商品库存
	 * @param goodsOwnerId
	 * @param goodsOwnerName
	 * @param setAgentPrice
	 * @param productId
	 * @param currency
	 * @param virtualStock
	 * @param totalStock
	 * @throws InterruptedException
	 * @throws IOException
	 */
	public static void modifyAgentProductBean(int goodsOwnerId,
			String goodsOwnerName, boolean setAgentPrice, String productId,
			String currency, int virtualStock, int totalStock) throws InterruptedException, IOException {

		AddAgentProductBean agentProductBean = AddAgentProductCallService
				.initAddAgentProduct(goodsOwnerId, goodsOwnerName,
						setAgentPrice);

		if (currency != null)
			agentProductBean.setCurrency(currency);

		ModifyAgentProductBean modifyAgentProductBean = AddAgentProductCallService
				.initModifyAgentProductBean(productId, agentProductBean);

		for (ModifyCatalogDto catalogDto : modifyAgentProductBean
				.getCatalogList()) {
			
			catalogDto.setVirtualStock(virtualStock);
			catalogDto.setStock(totalStock);
		}
			
		AddAgentProductCallService.modifyAgentProduct(modifyAgentProductBean);
	}
	/**
	 * 设置双通道模式
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static void setDualMode(long goodsOwnerId) throws ClientProtocolException, IOException {
		
		setShareTypeBean bean=new setShareTypeBean();
		setShareTypeCall call=new setShareTypeCall();
		
		bean.setMchId((int)goodsOwnerId);
		bean.setMchShareType(1);
		bean.setMchStatus(0);
		bean.setRemark("test");
	
		bean.setPayMode(3);
		//新字段
		bean.setMchSideBuy(1);//商家端购买1：二维码购买 2：直接购买
		bean.setDualMode(1);//双店模式0：正常模式（默认）1：双店模式
		
//		bean.setPlatformSupplier(true);
//		bean.setPlatformSupplierAliHpPayMode(1);
//		bean.setPlatformSupplierWxHpPayMode(1);
		
		call.setData(bean);
		call.callService();	
	}
	
	/**
	 * 创建供货商
	 * @throws Exception
	 * @throws JSONException
	 */
	public static Integer createApplySupplier(String country) throws JSONException, Exception {
		
		Integer mchId = DGSQBaseService.createIndependenceMch("USA");
		
		applySupplierBean applySupplierBean = GodmchManageCallService.initApplySupplier(mchId);
		
		applySupplierBean.setCountry(country);
		applySupplierBean.setPassword(TestDataManager.randomStr(9));
		
		applySupplierCall applySupplierCall = GodmchManageCallService.applySupplierCall(applySupplierBean);
		
		GodmchManageCallService.approveSupplier(mchId, applySupplierCall.getSupplierId());
		
		GodmchManageCallService.SetVip(applySupplierCall.getSupplierId());

		return applySupplierCall.getSupplierId();
	}
	
	/**
	 * 创建供货商
	 * @throws Exception
	 * @throws JSONException
	 */
	public static Integer createApplySupplier(String country, Integer mchId) throws JSONException, Exception {
		
		applySupplierBean applySupplierBean = GodmchManageCallService.initApplySupplier(mchId);
		
		applySupplierBean.setCountry(country);
		applySupplierBean.setPassword(TestDataManager.randomStr(9));
		
		applySupplierCall applySupplierCall = GodmchManageCallService.applySupplierCall(applySupplierBean);
		Integer supplierId = applySupplierCall.getSupplierId();

		GodmchManageCallService.approveSupplier(mchId, supplierId);
		GodmchManageCallService.SetVip(supplierId);

		// 更新供应商发布跨境商品权限
		mch_infoWapper wapper = new mch_infoWapper();
		wapper.updateProductBorderProperty(supplierId);

		return supplierId;
	}
	
	public static void editRetailShopProductRebate(String productId,
			Long storeId, Long goodsOwnerId, BigDecimal rebate)
			throws ClientProtocolException, InterruptedException, IOException {

		EditProductRebateBean editProductRebateBean = AddAgentProductCallService
				.initEditProductRebateBean(productId, storeId.intValue(),
						goodsOwnerId.intValue(), rebate.doubleValue());

		AddAgentProductCallService.EditProductRebateBean(editProductRebateBean);
	}
	
	/**
	 * 更新mchRelation为解绑状态
	 * @throws InterruptedException 
	 */
	public static void updateMchRelationToUnbind(Long goodsOwnerId) throws InterruptedException {
		
		mch_relationWapper test = new mch_relationWapper();
		
		test.updateMchRelationToUnbind(goodsOwnerId.intValue());
	}
	
	/**
	 * 创建一品多码代理商品发布
	 * 
	 * @param goodsOwnerId
	 *            商户id
	 * @param goodsOwnerName
	 *            商户名称
	 * @param setAgentPrice
	 *            是否设置给下级代理
	 * @param currency 币种
	 */
	public static String createMultiCodeAgentProduct(int goodsOwnerId,
			String goodsOwnerName, boolean setAgentPrice, String currency) throws IOException {

		AddAgentProductBean addAgentProductBean = AddAgentProductCallService
				.initAddMultiCodeAgentProduct(goodsOwnerId, goodsOwnerName, setAgentPrice);
		
		addAgentProductBean.setBrandId(10104);

		if (currency != null)
			addAgentProductBean.setCurrency(currency);
		
		List<CatalogDto> agentCatalogIdList = addAgentProductBean
				.getCatalogList();

		agentCatalogIdList.stream().forEach(catalogDto -> {
			catalogDto.setCostPrice(20d);
		});

		return AddAgentProductCallService.AddAgentProduct(addAgentProductBean);
	}

	/**
	 * 创建一品多码代理商品发布
	 *
	 * @param goodsOwnerId
	 *            商户id
	 * @param goodsOwnerName
	 *            商户名称
	 * @param setAgentPrice
	 *            是否设置给下级代理
	 * @param currency 币种
	 */
	public static String createMultiCodeAgentProductForPreSale(int goodsOwnerId,
															   String goodsOwnerName,
															   boolean setAgentPrice,
															   String currency,
															   int stock) throws IOException {

		AddAgentProductBean addAgentProductBean = AddAgentProductCallService
				.initAddMultiCodeAgentProduct(goodsOwnerId, goodsOwnerName, setAgentPrice);

		addAgentProductBean.setBrandId(10104);

		if (currency != null)
			addAgentProductBean.setCurrency(currency);

		List<CatalogDto> agentCatalogIdList = addAgentProductBean
				.getCatalogList();

		agentCatalogIdList.stream().forEach(catalogDto -> {
			catalogDto.setCostPrice(20d);
			catalogDto.setStock(stock);
		});

		return AddAgentProductCallService.AddAgentProduct(addAgentProductBean);
	}

	public static void main(String[] args) throws Exception {

		// String productId = DGSQBaseService.createAgentProduct(
		// (int) autotest_goodsOwnerId, autotest_goodsOwnerName, true);
		//
		// createmchBean createmchBean = DGSQBaseService
		// .bindChannel((int) autotest_goodsOwnerId);
		//
		// AgentProductBean agentProductBean =
		// DGSQBaseService.importAgentProduct(
		// createmchBean.getMchId(), "", productId,
		// (int) autotest_goodsOwnerId, true);
		//
		// createmchBean bean = DGSQBaseService.createAgent(
		// createmchBean.getMchId(), "CHN");
		
//		System.out.println(createGoodsOwner("USA"));
		
		DGSQBaseService.createGoodsOwner("HKG");
		
//		DGSQBaseService.setDualMode(502666058L);
		
//		System.out.println(createApplySupplier("JPN"));
		
//		System.out.println(DGSQBaseService.getCatalogPriceList(Arrays.asList("c6811247", "c6811248")).get(0).getCatalogId());
		
//		setDualMode(500583265);
		
//		System.out.println(getCurrencyConfig("USD").getExchangeRmbRate());
		
//		String productId = DGSQBaseService.createAgentProduct((int) autotest_goodsOwnerId,
//				autotest_goodsOwnerName, false, null, true);
//		
//		String catalogId = DGSQBaseService.getCatalogIdList(productId).get(0);
//		
//		DetailsCatalogDto catalog = DGSQBaseService.getProductStock((int) autotest_goodsOwnerId, productId,
//				catalogId);
//		
//		System.out.println(catalog.getVirtualStock());
//		
//		DGSQBaseService.modifyAgentProductBean((int) autotest_goodsOwnerId,
//				autotest_goodsOwnerName, false, productId, null);
//		
//		DetailsCatalogDto catalog1 = DGSQBaseService.getProductStock((int) autotest_goodsOwnerId, productId,
//				catalogId);
//		
//		System.out.println(catalog1.getVirtualStock());
		
//		List<YmtCatalogsI> ymtCatalogsIList = new YmtCatalogsIWapper()
//				.selectCatalogsByCatalogIdforList("c5277581");
//		
//		System.out.println(ymtCatalogsIList.get(0).getRootCatalogId());
		
//		System.out.println(new OrderCallService().createNewUser());
		
//		DGSQBaseService.createProvider(500002490);
//		DGSQBaseService.createServiceRelation(500002490, 500320011, 3);
		
//		DGSQBaseService.createIndependenceAgent(DGSQBaseService.createIndependenceMch("USA"), "HKG");

//		AgentProductBean agentProduct = DGSQBaseService.createProductByChain(
//				Arrays.asList(500002490L, 500004880L, 500004881L), true);
//
//		Logger.comment(String.format("代理商的国家：%s，代理商的Id：%s，代理商的商品：%s", "", "",
//				agentProduct.toString()));
		
		// 数据库插入小程序配置,dguser.wxappconfig
//		DGUserWapper wapper = new DGUserWapper();
//		wapper.insertWxAppConfig(502666058);
		
//		DGSQBaseService.createPromoters(502666058, 2);
	}
}